import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;

public class ExamPaperViewFrame extends JFrame {
    private int examId;
    private int studentId;
    private User teacher;
    private Exam exam;
    private User student;
    private ExamRecord examRecord;
    private List<Question> questions;
    private List<AnswerRecord> studentAnswers;

    // UI组件
    private JPanel questionsPanel;
    private JTextField totalScoreField;
    private JTextArea commentsArea;
    private JButton saveGradeButton;
    private JButton closeButton;

    // DAO
    private ExamDAO examDAO;
    private UserDAO userDAO;
    private QuestionDAO questionDAO;
    private AnswerRecordDAO answerRecordDAO;
    private ExamRecordDAO examRecordDAO;

    // 分数编辑字段映射
    private java.util.Map<Integer, JTextField> questionScoreFields;

    public ExamPaperViewFrame(int examId, int studentId, User teacher) {
        this.examId = examId;
        this.studentId = studentId;
        this.teacher = teacher;

        // 初始化DAO
        this.examDAO = new ExamDAO();
        this.userDAO = new UserDAO();
        this.questionDAO = new QuestionDAO();
        this.answerRecordDAO = new AnswerRecordDAO();
        this.examRecordDAO = new ExamRecordDAO();

        // 初始化分数字段映射
        this.questionScoreFields = new java.util.HashMap<>();

        // 加载数据
        loadData();

        initComponents();
        setupLayout();
        setupEvents();
        loadExamPaper();
    }

    private void loadData() {
        this.exam = examDAO.getExamById(examId);
        this.student = userDAO.getUserById(studentId);
        this.examRecord = examRecordDAO.getExamRecord(examId, studentId);
        this.questions = questionDAO.getQuestionsByExamId(examId);
        if (examRecord != null) {
            this.studentAnswers = answerRecordDAO.getAnswersByExamRecord(examRecord.getId());
        }
    }

    private void initComponents() {
        setTitle("试卷查看 - " + (exam != null ? exam.getTitle() : "考试"));
        setSize(1200, 900);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(true);

        // 字体设置
        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);

        // 题目面板
        questionsPanel = new JPanel();
        questionsPanel.setLayout(new BoxLayout(questionsPanel, BoxLayout.Y_AXIS));

        // 总分输入框
        totalScoreField = new JTextField();
        totalScoreField.setFont(new Font("微软雅黑", Font.BOLD, 18));
        totalScoreField.setPreferredSize(new Dimension(120, 40));
        totalScoreField.setHorizontalAlignment(JTextField.CENTER);
        totalScoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)));

        // 评语文本区域
        commentsArea = new JTextArea(4, 50);
        commentsArea.setFont(fieldFont);
        commentsArea.setLineWrap(true);
        commentsArea.setWrapStyleWord(true);
        commentsArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)));

        // 按钮
        saveGradeButton = new JButton("保存评分");
        saveGradeButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        saveGradeButton.setPreferredSize(new Dimension(120, 45));
        saveGradeButton.setBackground(new Color(40, 167, 69));
        saveGradeButton.setForeground(Color.WHITE);

        closeButton = new JButton("关闭");
        closeButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        closeButton.setPreferredSize(new Dimension(100, 45));
        closeButton.setBackground(new Color(108, 117, 125));
        closeButton.setForeground(Color.WHITE);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部信息面板
        JPanel topPanel = createTopPanel();

        // 主要内容面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 试卷内容滚动面板
        JScrollPane scrollPane = new JScrollPane(questionsPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "试卷内容",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        // 评分面板
        JPanel gradePanel = createGradePanel();

        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(gradePanel, BorderLayout.SOUTH);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        buttonPanel.add(saveGradeButton);
        buttonPanel.add(closeButton);

        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(70, 130, 180));
        panel.setPreferredSize(new Dimension(1200, 100));

        // 标题
        JLabel titleLabel = new JLabel("试卷查看与阅卷", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);

        // 信息面板
        JPanel infoPanel = new JPanel(new GridLayout(2, 2, 10, 5));
        infoPanel.setBackground(new Color(70, 130, 180));
        infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        Font infoFont = new Font("微软雅黑", Font.BOLD, 14);

        JLabel examLabel = new JLabel("考试: " + (exam != null ? exam.getTitle() : "未知"));
        examLabel.setFont(infoFont);
        examLabel.setForeground(Color.WHITE);

        JLabel studentLabel = new JLabel("学生: " + (student != null ? student.getRealName() : "未知"));
        studentLabel.setFont(infoFont);
        studentLabel.setForeground(Color.WHITE);

        String submitTime = "未提交";
        if (examRecord != null && examRecord.getSubmitTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            submitTime = sdf.format(examRecord.getSubmitTime());
        }
        JLabel timeLabel = new JLabel("提交时间: " + submitTime);
        timeLabel.setFont(infoFont);
        timeLabel.setForeground(Color.WHITE);

        String status = "未知";
        if (examRecord != null) {
            switch (examRecord.getStatus()) {
                case "submitted":
                    status = "已提交";
                    break;
                case "graded":
                    status = "已阅卷";
                    break;
                case "in_progress":
                    status = "进行中";
                    break;
                default:
                    status = examRecord.getStatus();
            }
        }
        JLabel statusLabel = new JLabel("状态: " + status);
        statusLabel.setFont(infoFont);
        statusLabel.setForeground(Color.WHITE);

        infoPanel.add(examLabel);
        infoPanel.add(studentLabel);
        infoPanel.add(timeLabel);
        infoPanel.add(statusLabel);

        panel.add(titleLabel, BorderLayout.CENTER);
        panel.add(infoPanel, BorderLayout.EAST);

        return panel;
    }

    private JPanel createGradePanel() {
        JPanel panel = new JPanel(new BorderLayout(15, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "评分区域",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 16),
                new Color(70, 130, 180)));

        // 分数面板
        JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 10));
        JLabel scoreLabel = new JLabel("总分:");
        scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        scoreLabel.setForeground(new Color(70, 130, 180));

        JLabel maxScoreLabel = new JLabel("/ " + (exam != null ? exam.getTotalScore() : "100"));
        maxScoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        scorePanel.add(scoreLabel);
        scorePanel.add(totalScoreField);
        scorePanel.add(maxScoreLabel);

        // 评语面板
        JPanel commentPanel = new JPanel(new BorderLayout(10, 5));
        JLabel commentLabel = new JLabel("评语:");
        commentLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));

        JScrollPane commentScrollPane = new JScrollPane(commentsArea);
        commentScrollPane.setPreferredSize(new Dimension(800, 100));

        commentPanel.add(commentLabel, BorderLayout.NORTH);
        commentPanel.add(commentScrollPane, BorderLayout.CENTER);

        panel.add(scorePanel, BorderLayout.NORTH);
        panel.add(commentPanel, BorderLayout.CENTER);

        return panel;
    }

    private void setupEvents() {
        saveGradeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveGrade();
            }
        });

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }

    private void loadExamPaper() {
        questionsPanel.removeAll();

        if (questions == null || questions.isEmpty()) {
            JLabel noQuestionsLabel = new JLabel("没有找到题目", JLabel.CENTER);
            noQuestionsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
            questionsPanel.add(noQuestionsLabel);
            return;
        }

        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            AnswerRecord studentAnswer = findStudentAnswer(question.getId());

            JPanel questionPanel = createQuestionPanel(i + 1, question, studentAnswer);
            questionsPanel.add(questionPanel);
            questionsPanel.add(Box.createVerticalStrut(15));
        }

        // 加载已有评分
        if (examRecord != null) {
            totalScoreField.setText(String.valueOf(examRecord.getTotalScore()));
            // 暂时移除评语功能，因为ExamRecord没有comments字段
            // if (examRecord.getComments() != null) {
            // commentsArea.setText(examRecord.getComments());
            // }
        }

        questionsPanel.revalidate();
        questionsPanel.repaint();
    }

    private AnswerRecord findStudentAnswer(int questionId) {
        if (studentAnswers != null) {
            for (AnswerRecord answer : studentAnswers) {
                if (answer.getQuestionId() == questionId) {
                    return answer;
                }
            }
        }
        return null;
    }

    private JPanel createQuestionPanel(int questionNumber, Question question, AnswerRecord studentAnswer) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));
        panel.setBackground(Color.WHITE);

        // 题目标题 - 添加题型显示
        String questionTypeText = getQuestionTypeText(question.getQuestionType());
        JLabel titleLabel = new JLabel(
                "第" + questionNumber + "题 [" + questionTypeText + "] (" + question.getScore() + "分)");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setForeground(new Color(70, 130, 180));

        // 题目内容
        JTextArea questionTextArea = new JTextArea(question.getQuestionText());
        questionTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        questionTextArea.setLineWrap(true);
        questionTextArea.setWrapStyleWord(true);
        questionTextArea.setEditable(false);
        questionTextArea.setBackground(new Color(248, 249, 250));
        questionTextArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 学生答案面板
        JPanel answerPanel = new JPanel(new BorderLayout(5, 5));
        JLabel answerLabel = new JLabel("学生答案:");
        answerLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));

        String answerText = studentAnswer != null ? formatStudentAnswer(question, studentAnswer.getAnswerText())
                : "未作答";
        JTextArea answerTextArea = new JTextArea(answerText);
        answerTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        answerTextArea.setLineWrap(true);
        answerTextArea.setWrapStyleWord(true);
        answerTextArea.setEditable(false);
        answerTextArea.setBackground(new Color(255, 248, 220));
        answerTextArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        answerPanel.add(answerLabel, BorderLayout.NORTH);
        answerPanel.add(answerTextArea, BorderLayout.CENTER);

        // 正确答案面板
        JPanel correctAnswerPanel = new JPanel(new BorderLayout(5, 5));
        JLabel correctLabel = new JLabel("正确答案:");
        correctLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        correctLabel.setForeground(new Color(40, 167, 69));

        String correctAnswerText = getCorrectAnswerText(question);
        JTextArea correctTextArea = new JTextArea(correctAnswerText);
        correctTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        correctTextArea.setLineWrap(true);
        correctTextArea.setWrapStyleWord(true);
        correctTextArea.setEditable(false);
        correctTextArea.setBackground(new Color(248, 255, 248));
        correctTextArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        correctAnswerPanel.add(correctLabel, BorderLayout.NORTH);
        correctAnswerPanel.add(correctTextArea, BorderLayout.CENTER);

        // 得分显示 - 可编辑
        JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        double score = studentAnswer != null ? studentAnswer.getScore() : 0.0;

        // 创建可编辑的分数显示
        JPanel editableScorePanel = createEditableScorePanel(question, score);
        scorePanel.add(editableScorePanel);

        // 如果是选择题，显示选项
        if (question.isChoiceQuestion() && question.getOptions() != null) {
            JPanel optionsPanel = new JPanel();
            optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS));
            optionsPanel.setBorder(BorderFactory.createTitledBorder("选项"));

            for (QuestionOption option : question.getOptions()) {
                JLabel optionLabel = new JLabel(option.getOptionLabel() + ". " + option.getOptionText());
                optionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                if (option.isCorrect()) {
                    optionLabel.setForeground(new Color(40, 167, 69));
                    optionLabel.setText(optionLabel.getText() + " ✓");
                }
                optionsPanel.add(optionLabel);
            }

            JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
            contentPanel.add(questionTextArea, BorderLayout.NORTH);
            contentPanel.add(optionsPanel, BorderLayout.CENTER);

            // 答案区域
            JPanel answersPanel = new JPanel(new GridLayout(1, 2, 10, 0));
            answersPanel.add(answerPanel);
            answersPanel.add(correctAnswerPanel);

            panel.add(titleLabel, BorderLayout.NORTH);
            panel.add(contentPanel, BorderLayout.CENTER);

            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.add(answersPanel, BorderLayout.CENTER);
            bottomPanel.add(scorePanel, BorderLayout.SOUTH);
            panel.add(bottomPanel, BorderLayout.SOUTH);
        } else {
            // 非选择题布局
            JPanel answersPanel = new JPanel(new GridLayout(1, 2, 10, 0));
            answersPanel.add(answerPanel);
            answersPanel.add(correctAnswerPanel);

            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.add(answersPanel, BorderLayout.CENTER);
            bottomPanel.add(scorePanel, BorderLayout.SOUTH);

            panel.add(titleLabel, BorderLayout.NORTH);
            panel.add(questionTextArea, BorderLayout.CENTER);
            panel.add(bottomPanel, BorderLayout.SOUTH);
        }

        return panel;
    }

    private String formatStudentAnswer(Question question, String answerText) {
        if (answerText == null || answerText.trim().isEmpty()) {
            return "未作答";
        }

        if (question.isTrueFalseQuestion()) {
            return "true".equals(answerText) ? "正确 (True)" : "错误 (False)";
        }

        return answerText;
    }

    private String getCorrectAnswerText(Question question) {
        if (question.isChoiceQuestion() && question.getOptions() != null) {
            StringBuilder correct = new StringBuilder();
            for (QuestionOption option : question.getOptions()) {
                if (option.isCorrect()) {
                    if (correct.length() > 0)
                        correct.append(", ");
                    correct.append(option.getOptionLabel()).append(". ").append(option.getOptionText());
                }
            }
            return correct.toString();
        } else if (question.isTrueFalseQuestion()) {
            String correctAnswer = question.getCorrectAnswer();
            if (correctAnswer != null) {
                return "true".equals(correctAnswer) ? "正确 (True)" : "错误 (False)";
            }
            return "未设置正确答案";
        } else if (question.isFillBlankQuestion()) {
            String correctAnswer = question.getCorrectAnswer();
            return correctAnswer != null && !correctAnswer.trim().isEmpty() ? correctAnswer : "未设置标准答案";
        } else {
            return "需要教师评分";
        }
    }

    private String getQuestionTypeText(String type) {
        switch (type) {
            case "single_choice":
                return "单选题";
            case "multiple_choice":
                return "多选题";
            case "true_false":
                return "判断题";
            case "fill_blank":
                return "填空题";
            case "essay":
                return "问答题";
            default:
                return type;
        }
    }

    private JPanel createEditableScorePanel(Question question, double currentScore) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        panel.setOpaque(false);

        JLabel scoreLabel = new JLabel("得分:");
        scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        scoreLabel.setForeground(new Color(220, 53, 69));

        // 创建可编辑的分数字段
        JTextField scoreField = new JTextField(6);
        scoreField.setFont(new Font("微软雅黑", Font.BOLD, 14));
        scoreField.setHorizontalAlignment(JTextField.CENTER);
        scoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 53, 69), 2),
                BorderFactory.createEmptyBorder(2, 5, 2, 5)));
        scoreField.setText(String.valueOf(currentScore));

        // 设置颜色
        updateScoreFieldColor(scoreField, currentScore, question.getScore());

        // 添加输入验证和自动计算
        scoreField.addActionListener(e -> {
            validateAndUpdateQuestionScore(question, scoreField);
            calculateAndUpdateTotalScore();
        });

        scoreField.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                validateAndUpdateQuestionScore(question, scoreField);
                calculateAndUpdateTotalScore();
            }
        });

        JLabel maxScoreLabel = new JLabel("/" + question.getScore());
        maxScoreLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        maxScoreLabel.setForeground(new Color(108, 117, 125));

        // 保存到映射中
        questionScoreFields.put(question.getId(), scoreField);

        panel.add(scoreLabel);
        panel.add(scoreField);
        panel.add(maxScoreLabel);

        return panel;
    }

    private void updateScoreFieldColor(JTextField scoreField, double score, double maxScore) {
        if (score == maxScore) {
            scoreField.setForeground(new Color(40, 167, 69)); // 满分绿色
        } else if (score > 0) {
            scoreField.setForeground(new Color(255, 193, 7)); // 部分分数黄色
        } else {
            scoreField.setForeground(new Color(220, 53, 69)); // 零分红色
        }
    }

    private void validateAndUpdateQuestionScore(Question question, JTextField scoreField) {
        System.out.println("=== ExamPaperViewFrame 验证并更新题目分数 ===");
        System.out.println("questionId: " + question.getId() + ", 输入分数: " + scoreField.getText());

        try {
            String text = scoreField.getText().trim();
            if (text.isEmpty()) {
                scoreField.setText("0");
                return;
            }

            double score = Double.parseDouble(text);
            if (score < 0) {
                score = 0;
                scoreField.setText("0");
                JOptionPane.showMessageDialog(this, "分数不能为负数！", "输入错误", JOptionPane.WARNING_MESSAGE);
            } else if (score > question.getScore()) {
                score = question.getScore();
                scoreField.setText(String.valueOf(question.getScore()));
                JOptionPane.showMessageDialog(this, "分数不能超过满分！", "输入错误", JOptionPane.WARNING_MESSAGE);
            }

            // 更新颜色
            updateScoreFieldColor(scoreField, score, question.getScore());

            // 更新数据库中的分数
            if (examRecord != null) {
                System.out.println("更新数据库分数: examRecordId=" + examRecord.getId() +
                        ", questionId=" + question.getId() + ", score=" + score);
                boolean updateResult = answerRecordDAO.updateAnswerScore(examRecord.getId(), question.getId(), score);
                System.out.println("ExamPaperViewFrame 分数更新结果: " + updateResult);
            } else {
                System.out.println("警告: examRecord 为 null，无法更新分数");
            }

        } catch (NumberFormatException e) {
            System.out.println("数字格式错误: " + e.getMessage());
            scoreField.setText("0");
            JOptionPane.showMessageDialog(this, "请输入有效的数字！", "输入错误", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void calculateAndUpdateTotalScore() {
        double totalScore = 0.0;

        for (Question question : questions) {
            JTextField scoreField = questionScoreFields.get(question.getId());
            if (scoreField != null && !scoreField.getText().trim().isEmpty()) {
                try {
                    double score = Double.parseDouble(scoreField.getText().trim());
                    totalScore += score;
                } catch (NumberFormatException e) {
                    // 忽略无效输入
                }
            }
        }

        totalScoreField.setText(String.valueOf(totalScore));
    }

    private void saveGrade() {
        if (examRecord == null) {
            JOptionPane.showMessageDialog(this, "找不到考试记录！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            // 重新计算总分
            calculateAndUpdateTotalScore();

            double totalScore = Double.parseDouble(totalScoreField.getText().trim());
            if (totalScore < 0 || (exam != null && totalScore > exam.getTotalScore())) {
                JOptionPane.showMessageDialog(this, "分数超出范围！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            examRecord.setTotalScore(totalScore);
            examRecord.setStatus("graded");

            if (examRecordDAO.updateExamRecord(examRecord)) {
                JOptionPane.showMessageDialog(this, "评分保存成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "评分保存失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入有效的分数！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}